package com.example.demo.rocketmq.provider.service;

import com.example.demo.rocketmq.RocketUtils;
import com.example.demo.rocketmq.vo.OrderChange;
import lombok.Getter;
import lombok.Setter;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.util.Assert;

import java.lang.reflect.InvocationTargetException;

public abstract class AbstractCommonProviderService implements CommonProviderService {

    @Setter
    private String beanName = null;

    @Setter
    @Getter
    private String topicName = "order-topic";
    public final RocketMQTemplate rocketMQTemplate;

    public AbstractCommonProviderService(RocketMQTemplate rocketMQTemplate) {
        this.rocketMQTemplate = rocketMQTemplate;
    }

    public void send(String msg) {
        rocketMQTemplate.send(getTopicName(), RocketUtils.buildMsg(msg));
    }

    public void sendOneWay(String msg) {
        rocketMQTemplate.sendOneWay(getTopicName(), RocketUtils.buildMsg(msg));
    }

    /**
     * 发送半消息
     *
     * @param methodName
     * @param parameterTypes
     * @param msg
     * @return
     */
    public TransactionSendResult sendHalfmessafe(String methodName, String parameterTypes, OrderChange msg) {
        Assert.notNull(beanName, "beanName must not be empty");
        return rocketMQTemplate.sendMessageInTransaction(topicName, RocketUtils.buildMsg(beanName, methodName, parameterTypes, msg), msg);
    }

    @Override
    public void localTransactionExeute(Object o, String methodName, Class<?> clazz, Object args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        o.getClass().getMethod(methodName, clazz).invoke(o, args);
    }

    @Override
    public String getBeanName() {
        return beanName;
    }

}
